package com.example.springbootdemo.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: HttpUtils
 * @Description:
 * @Author: TXW
 * @Date: 2023-07-24
 */

public class HttpUtils {

    public static String sendHeaderPostRequest(String url, Map<String,String> header, JSONObject jsonParams) throws IOException {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();

        try {
            // 创建URL对象
            URL requestUrl = new URL(url);

            // 打开连接
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setDoOutput(true);

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            for (String key: header.keySet()) {
                connection.setRequestProperty(key, header.get(key));
            }

            // 将参数转换为字节数组并写入请求体
            byte[] postDataBytes = jsonParams.toString().getBytes("UTF-8");
            connection.getOutputStream().write(postDataBytes);

            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } finally {
            // 关闭连接和读取器
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                reader.close();
            }
        }

        return response.toString();
    }

    public static void main(String[] args) throws IOException {
//        String url = "http://localhost:8088/credit/registerController/registrationAdd";
//        String s1 = HttpUtils.sendHeaderPostRequest(url, new HashMap<>(), new JSONObject());

        String info ="学习字符转换";
        //通常乱码的情况是 两个不兼容的编码相互转换

        //UTF_8 转 iso-8859-1   iso-8859-1不兼容中文 会乱码
        String s = new String(info.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        String s1 = new String(info.getBytes(StandardCharsets.UTF_8), StandardCharsets.US_ASCII);
//        System.out.println(s);
        System.out.println(s1);
        // iso-8859-1 转 UTF_8
//        String strInfo = new String(s.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//        System.out.println(strInfo);
    }
}
